<?php

namespace App\Services;

use App\Models\BookIsbn;
use App\Models\Cart;
use App\Models\Cate;
use App\Models\Goods;
use App\Models\ShopSellRank;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class GraspService
{
    /**
     * 转转客服端
     *
     * @return Client
     */
    public static function zzClient()
    {
        $cookie  = 'PPU="TT=c121bf72ca8e6a4129967ed7779e2c9351a6f01b&UID=43149020539921&SF=ZHUANZHUAN&SCT=1576473505861&V=1&ET=1579061905861"; Version=1; Domain=zhuanzhuan.com; Max-Age=2592000; Expires=Wed, 15-Jan-2020 04:18:43 GMT; Path=/';
        $headers = [
            ':authority' => 'app.zhuanzhuan.com',
            ':scheme'    => 'https',
            'cookie'     => $cookie,
            'dnt'        => '1',
            'origin'     => 'https://m.zhuanzhuan.com',
            'referer'    => 'https://m.zhuanzhuan.com/cycle/ZZBook/index.html?fromChannel=gzhcd_home',
        ];
        $client  = new Client(
            [
                'cookies' => true,
                'timeout' => 20,
                'headers' => $headers,
            ]
        );
        return $client;
    }

    /**
     * 获取多抓鱼header
     *
     * @param $userId
     *
     * @return \Psr\Http\Message\StreamInterface
     */
    public static function getDzyHeader($userId)
    {
        $url     = "http://47.95.194.199:8888/?userid=" . $userId;
        $client  = new Client(
            [
                'timeout' => 20,
            ]
        );
        $res     = $client->request('get', $url);
        $content = $res->getBody()->getContents();
        return json_decode($content, true);
    }

    /**
     * 封装请求多抓鱼客服端
     *
     * @return Client
     */
    public static function dzyClient($userId, $cookie)
    {

        $headers           = self::getDzyHeader($userId);
        $headers['Cookie'] = $cookie;
        $client            = new Client(
            [
                'cookies' => true,
                'timeout' => 20,
                'headers' => $headers,
            ]
        );
        return $client;
    }

    /**
     * 封装多抓鱼请求
     *
     * @param        $url
     * @param string $method
     * @param array  $param
     * @param string $userId
     * @param string $cookie
     *
     * @return bool|mixed
     */
    public static function dzyRequest($url, $method = 'get', $param = [], $userId = '', $cookie = '')
    {
        if (Cache::has('dzy_request_error')) {
            return false;
        }
        if (empty($userId) && empty($cookie)) {
            $userPrefix = config('pull_user');
            $userId     = config($userPrefix . '_dzy_userid');
            $cookie     = config($userPrefix . '_dzy_cookie');
        }
        $client = self::dzyClient($userId, $cookie);
        try {
            $res     = $client->request($method, $url, $param);
            $content = $res->getBody()->getContents();
            return json_decode($content, true);
        } catch (RequestException $e) {
            $code = $e->getResponse()->getStatusCode();
            if ($code == 403) {
                $content = json_decode($e->getResponse()->getBody()->getContents(), true);
                Log::error("请求多抓鱼没有权限", $content);
                return false;
            } elseif ($code == 401) {
                Log::error('请求多抓鱼失败', [$url, $param, $content]);
                Cache::put('dzy_request_error', 1);
                //发模板消息通知
                WechatService::sendMsg(['多抓鱼请求失败', '请更新权限数据']);
                return false;
            } else {
                $content = $e->getResponse()->getBody()->getContents();
                Log::error("请求服务器错误", [$content]);
                return false;
            }
        }

    }

    /**
     * 漫游鲸客服端
     *
     * @return Client
     */
    public static function myjClient()
    {
        $headers = [
            'Authorization' => config('myj_auth'),
            'Referer'       => 'https://servicewechat.com/wx816dc6e826dcc6b5/271/page-frame.html',
            'Host'          => 'app.manyoujing.net',
        ];
        $client  = new Client(
            [
                'cookies' => true,
                'timeout' => 20,
                'headers' => $headers,
            ]
        );
        return $client;
    }

    public static function goodList($shopname)
    {
        $microtime = self::microtime();
        $preg      = "/^http(s)?:\\/\\/.+/";
        if (preg_match($preg, $shopname)) {
            $url = $shopname;
        } else {
            $url = "http://search.kongfz.com/product_result/?status=1&shopname=" . $shopname . "&pagenum=1&ajaxdata=1&type=1&_=" . $microtime;
        }

        $url = str_replace(array("\r\n", "\r", "\n"), "", $url);

        $parts = parse_url($url);

        parse_str($parts['query'], $query);
        $data = self::exeCurl($url);

        if ($data == false) {
            return [];
        }
        $data = json_decode($data, true);
        if (!$data['data']['itemList']) {
            return [];
        }

        $itemList    = $data['data']['itemList'];
        $other       = $data['other'];
        $total       = $other['total']; //总数
        $page_number = $other['page_count']; //总页数
        $curpage     = $other['curpage']; //当前页
        self::addGood($itemList);
        if ($curpage >= $page_number) {
            return false;
        }
        $next_number = $query['pagenum'] + 1;
        $next_url    = "http://search.kongfz.com/product_result/?status=" . $query['status'] . "&shopname=" . $query['shopname'] . "&pagenum=" . $next_number . "&ajaxdata=" . $query['ajaxdata'] . "&type=" . $query['type'] . "&_=" . $query['_'];
        $res         =
            [
                'total'       => $total,
                'page_number' => $page_number,
                'curpage'     => $curpage + 1,
                'next_url'    => $next_url,
                'page_count'  => $total,
            ];
        return $res;
    }

    /**
     * 批量写入商品
     *
     * @Author   wangwenfan
     * @DateTime 2019-12-03
     *
     * @param    [type]     $itemList [description]
     */
    public static function addGood($itemList, $new = false)
    {
        $created_at = Carbon::now()->toDateTimeString();

        //写入数据库
        foreach ($itemList as $item) {
            $data = [
                'item_id'     => $item['itemid'],
                'title'       => $item['itemname'],
                'shop_id'     => $item['shopid'],
                'user_id'     => $item['userid'],
                'price'       => $item['price'],
                'url'         => "http://book.kongfz.com/" . $item['shopid'] . '/' . $item['itemid'],
                'img_url'     => $item['bigimgurl'] ?? '',
                'date'        => $item['updatetime'],
                'pinxiang'    => $item['qualityname'],
                'created_at'  => $created_at,
                'updated_at'  => $created_at,
                'add_time'    => $item['addtime'],
                'areaname'    => $item['areaname'] ?? '',
                'bindingname' => $item['bindingname'] ?? '',
                'author'      => $item['author'] ?? '',
                'press'       => $item['press'],
                'shopname'    => $item['shopname'],
                'isbn'        => $item['isbn'],
                'cate_id'     => $item['catid'],
            ];
            $cate = Cate::where('cate_id', $item['catid'])->first();
            if ($cate) {
                if ($cate['pid'] != 2) {
                    //非图书商品跳过
                    continue;

                    // $data['isbn'] = $item['isbn'] ? $item['isbn'] : 2;
                } else {
                    $data['isbn'] = $item['isbn'] ? $item['isbn'] : 3; //待修改的图书isbn
                }
            } else {
//                $data['isbn'] = $item['isbn'] ? $item['isbn'] : 2;
                //其他分类跳过
                continue;
            }
            $good = Goods::where('item_id', $item['itemid'])->first();
            if (!$good) {
                //更新店铺价格表数量
                self::updateShopPriceNumber($item['shopid'], $item['price']);
                GoodService::addGoods($data);
            }
            //查询豆瓣基础数据，没有就爬取新的商品
            if ($good['isbn'] > 3) {
                $bookisbn = BookIsbn::where('isbn13', $data['isbn'])->orWhere('isbn10', $data['isbn'])->first();
                if (is_null($bookisbn)) {
                    Log::info("爬取豆瓣数据：" . $data['isbn']);
                    $douban = DoubanService::isbnBook($data['isbn']);
                    if (!$douban || isset($douban['code'])) {
                        Log::error("爬取豆瓣失败:", [$douban]);
                        continue;
                    }
                    GoodService::insertDoubanBook($douban);
                } else {
                    Log::info("书库存在：" . $data['isbn']);
                }
            }
            //更新isbn数量
            self::updateIsbnTable($data['isbn']);
        }
        return true;
    }

    /**
     * 新入库图书更新isbn表
     *
     * @param $isbn
     *
     * @return bool
     */
    public static function updateIsbnTable($isbn)
    {
        if ($isbn != 3) {
            $book = BookIsbn::where('isbn10', $isbn)->orWhere('isbn13', $isbn)->first();
            if (!is_null($book)) {
                $book->sell_count = $book->sell_count + 1;
                return $book->save();
            } else {
                Log::error($isbn . ":数据不存在!");
            }
        }
        return false;
    }

    /**
     * 更新店铺价格数量
     *
     * @Author   wangwenfan
     * @DateTime 2019-12-04
     *
     * @param    [type]     $shopId [description]
     * @param    [type]     $price  [description]
     *
     * @return   [type]             [description]
     */
    public static function updateShopPriceNumber($shopId, $price)
    {
        $price    = intval($price);
        $priceSet = ConfigService::generatePrice();
        foreach ($priceSet as $priceTier) {

            if ($price >= $priceTier['start_price'] && $price <= $priceTier['end_price']) {
                $priceRange = intval($priceTier['start_price']) . '-' . intval($priceTier['end_price']);
                $rank       = ShopSellRank::where('shop_id', $shopId)->where('price_range', $priceRange)->first();
                if ($rank) {
                    $rank->sell_number = $rank->sell_number + 1;
                    $rank->save();
                } else {
                    $data = ['shop_id' => $shopId, 'price_range' => $priceRange, 'sell_number' => 1];
                    ShopSellRank::insert($data);
                }
            }
        }
    }

    public static function exeCurl($url, $referer = "http://search.kongfz.com", $proxy = '')
    {

        $headers = self::randIp();
        $curl    = curl_init();
        if ($proxy) {
            $proxyServer = "http://dyn.horocn.com:50000";
            $proxyUser   = "LQSB1648620605128398";
            $proxyPass   = "1zZ45sXF73zB";
            // 设置代理服务器
            curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
            curl_setopt($curl, CURLOPT_PROXY, $proxyServer);
            // 设置隧道验证信息
            curl_setopt($curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
            curl_setopt($curl, CURLOPT_PROXYUSERPWD, "{$proxyUser}:{$proxyPass}");
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_REFERER, $referer);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_USERAGENT,
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0"); //模拟浏览器类型
        curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl);

        if (curl_errno($curl)) {
            return false;
        } else {
            curl_close($curl);
        }
        return $tmpInfo;

    }

    /**
     * @param $headers
     * @param $url
     *
     * @return mixed
     * @throws \Exception
     */
    public static function exeHttp($headers, $url, $mentod = 'get', $param = [])
    {

        $client = new Client(
            [
                'cookies' => true,
                'timeout' => 20,
                'headers' => $headers,
            ]
        );
        $res    = $client->request($mentod, $url, $param);
        $conent = $res->getBody()->getContents();
        if ($res->getStatusCode() != 200) {
            throw new \Exception("请求失败，没有权限");
        }
        return json_decode($conent, true);
    }

    /**
     * 搜索多抓鱼商品
     */
    public static function searchDzy($isbn)
    {
        $url = "https://www.duozhuayu.com/api/search?is_in_stock_list=0&type=normal&q=" . $isbn . "&search_from=auto_search";

    }

    //此函数提供了国内的IP地址
    public static function randIP()
    {
        $ip_long                    = array(
            array('607649792', '608174079'), //36.56.0.0-36.63.255.255
            array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
            array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
            array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
            array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
            array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
            array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
            array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
            array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
            array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
        );
        $rand_key                   = mt_rand(0, 9);
        $ip                         = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
        $headers['CLIENT-IP']       = $ip;
        $headers['X-FORWARDED-FOR'] = $ip;

        $headerArr = array();
        foreach ($headers as $n => $v) {
            $headerArr[] = $n . ':' . $v;
        }
        return $headerArr;
    }

    public static function microtime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return intval($msectime);

    }

    public static function kwIsbnGoods()
    {
        //key是搜索词，isbn
        $url = "http://search.kongfz.com/product_result/?key=9787532942138&status=0&_stpmt=eyJzZWFyY2hfdHlwZSI6ImFjdGl2ZSJ9&pagenum=1&ajaxdata=1&type=1&_=1576139115507";
    }

    //转转批量加入购物车
    public static function addCartZZ()
    {
        $goods = Cart::where('zhuanzhuan', 0)->get();
        foreach ($goods as $num => $good) {
            print "当前第" . $num . "个\n";
            $ret = self::zhuanzhuanCart($good->isbn);
            if ($ret === 0) {
                //写入数据库
                $good->zhuanzhuan = 1;
                $res              = $good->save();
                var_dump($res);
            } else {
                continue;
            }

        }
    }

    public static function zhuanzhuanCart($isbn)
    {
        print "isbn:" . $isbn . "\n";
        $url    = "https://app.zhuanzhuan.com/zzopen/sellbook/bookSearch";
        $client = self::zzClient();
        $param  = [
            'multipart' => [
                [
                    'name'     => 'fromChannel',
                    'contents' => 'gzhcd_home',
                ],
                [
                    'name'     => 'query',
                    'contents' => $isbn,
                ],
                [
                    'name'     => 'pageNum',
                    'contents' => '1',
                ],
                [
                    'name'     => 'sf',
                    'contents' => '1',
                ],
                [
                    'name'     => 'requestMark',
                    'contents' => '1576139873693',
                ],
            ],
        ];

        $res = $client->request('post', $url, $param);

        if ($res->getStatusCode() != 200) {
            Log::error('请求转转失败', [$url, $param]);
            return false;
        }
        $conent   = $res->getBody()->getContents();
        $resData  = json_decode($conent, true);
        $respData = $resData['respData'];
        if (isset($respData['list'])) {
            //有货
            print "有货\n";
            Log::info("转转有货", ['isbn' => $isbn]);
            return 0;
        } elseif (isset($respData['noStockList'])) {
            //无货，加入到货提醒
            $infoId  = $respData['noStockList'][0]['infoId'];
            $infoUrl = "https://app.zhuanzhuan.com/zzopen/sellbook/registerArrivalReminder?fromChannel=gzhcd_home&infoId=" . $infoId . "&init_from=";
            $res2    = $client->request('get', $infoUrl);
            $conent2 = $res2->getBody()->getContents();
            print($conent2 . "\n");
            $zzret = json_decode($conent2, true);
            return $zzret['respCode'];
        }
    }

    public static function addCartMyj()
    {
        $goods = Cart::where('myj', 0)->get();
        foreach ($goods as $num => $good) {
            print "当前第" . $num . "个\n";
            $ret = self::myjCart($good->title, $good->isbn);
            if ($ret === 0) {
                //写入数据库
                $good->myj = 1;
                $res       = $good->save();
                var_dump($res);
            } else {
                print "没有这个商品\n";
                continue;
            }

        }
    }

    public static function myjCart($title, $isbn)
    {
        $keywords = urlencode($title);
        //查询商品
        $seoUrl = "https://app.manyoujing.net/v2/goods/search/no/stock?keyword=" . $keywords . "&page_index=1&page_size=10";
        $client = self::myjClient();
        $res    = $client->request('get', $seoUrl);
        if ($res->getStatusCode() != 200) {
            Log::error('请求漫游鲸失败', [$seoUrl, $keywords]);
            return false;
        }
        $content      = $res->getBody()->getContents();
        $contentArray = json_decode($content, true);
        if (isset($contentArray['data']['list'])) {
            $lists = $contentArray['data']['list'];
            foreach ($lists as $good) {
                if (!isset($good['description_units'])) {
                    continue;
                }
                $goodIsbn = '';
                foreach ($good['description_units'] as $units) {
                    if ($units['name'] == 'ISBN') {
                        $goodIsbn = $units['value'];
                    }
                }
                if ($goodIsbn == $isbn) {
                    //订阅
                    $id       = $good['id'];
                    $subUrl   = "https://app.manyoujing.net/v2/favorites/notice/arrival/switch";
                    $param    = ['spu_ids' => [$id], 'notice' => 1];
                    $res2     = $client->request('post', $subUrl, ['json' => $param]);
                    $content2 = $res2->getBody()->getContents();
                    $result   = json_decode($content2, true);
                    return $result['code'];

                } else {
                    return false;
                }
            }
        }

    }

    /**
     * 多抓鱼加入购物车
     */
    public static function addCartDzy()
    {
        $goods = Cart::all();
        $i     = 0;
        foreach ($goods as $good) {
            $i++;
            $content = self::execAddDzyCart($good->item_id);
            if (!$content) {
                continue;
            }
            $resData = json_decode($content, true);
            var_dump($resData['book']['title']);
            print "当前第：" . $i . "个\n";
            sleep(2);
        }
    }

    /**
     * 执行加入购物车
     *
     * @param $item_id
     *
     * @return bool|string
     */
    public static function execAddDzyCart($item_id, $uid = '', $cookie = '')
    {
        $url   = "https://www.duozhuayu.com/api/user/cart";
        $param = [
            'json' => ['bookId' => $item_id, 'inStockRemind' => true],
        ];
        return self::dzyRequest($url, 'post', $param, $uid, $cookie);
    }

    /**
     * 删除购物车
     *
     * @param        $uid
     * @param        $item_id
     * @param string $cookie
     *
     * @return bool|mixed
     */
    public static function deleteCart($url='https://www.duozhuayu.com/api/user/cart')
    {
        $uid    = '212257903313158199';
        $cookie = '_ga=GA1.2.721106630.1571902246; Hm_lvt_046a9150e95f58699927e236d330965a=1602468919,1603340454; _gid=GA1.2.2055669458.1603865331; Hm_lpvt_046a9150e95f58699927e236d330965a=1603866772; fish_c0="2|1:0|10:1603866769|7:fish_c0|24:MjEyMjU3OTAzMzEzMTU4MTk5|53f20703e583689b6bf13faf88bc8a998fc53a41567a158db1a7236dc322d6fd"; _gat=1';

        $cart = self::findDzyCart($url,$uid, $cookie, true);

        if ($data = $cart['data']) {
            foreach ($data as $d) {
                $item_id = $d['item']['id'];
                print_r("开始删除:".$item_id."\n");
                $url     = "https://www.duozhuayu.com/api/user/cart/" . $item_id;
                $ret =  self::dzyRequest($url, 'delete', [], $uid, $cookie);
                print_r($ret);
            }
            if (isset( $cart['paging']['next'])){
                print_r("开始删除下一页:".$cart['paging']['next'].'\n');
                self::deleteCart($cart['paging']['next']);
            }

        }




    }

    /**
     * 关键词搜索多抓鱼无库存商品
     *
     * @param $keywords
     *
     * @return bool|mixed
     */
    public static function dzyIsbnGood($keywords)
    {
        $url = "https://www.duozhuayu.com/api/search?is_in_stock_list=0&type=normal&q=" . $keywords . "&search_from=key_press";
        return self::dzyRequest($url);
    }

    /**
     * 查询购物车
     */
    public static function findDzyCart($url = "https://www.duozhuayu.com/api/user/cart",$user_id = '', $cookie = '', $is_all = false)
    {
        $ret = self::dzyRequest($url, 'get', [], $user_id, $cookie);
        return $is_all == true ? $ret : $ret['data'];
    }

    /**
     * 锁定多抓鱼商品
     *
     * @param $id
     *
     * @return bool|string
     */
    public static function lockDzyGood($id)
    {
        $url   = "https://www.duozhuayu.com/api/user/cart/" . $id . "/lock";
        $param = [
            'json' => [
                'payWay' => 'wechat_qrcode',
            ],
        ];
        return self::dzyRequest($url, 'post', $param);
    }

    /**
     * 锁定前加入购物车
     *
     * @param $id
     *
     * @return bool|mixed
     */
    public static function lockAddCart($id, $catParam)
    {
        Log::info("预定购物车参数:", $catParam);
        $url = "https://www.duozhuayu.com/api/user/cart/" . $id;
        $res = self::dzyRequest($url, 'patch', ['json' => $catParam]);
//        Log::info("预定购物车",$res);
        return $res;
    }

}
